package com.wzm.moviepic.fragment;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.wzm.bean.AdInfo;
import com.wzm.bean.MovieInfo;
import com.wzm.bean.PicInfo;
import com.wzm.cache.ConfigCache;
import com.wzm.db.DBHelper;
import com.wzm.manager.AppConfig;
import com.wzm.manager.AppManager;
import com.wzm.moviepic.AppApplication;
import com.wzm.moviepic.R;
import com.wzm.moviepic.weight.ScrollTextView;
import com.wzm.moviepic.weight.photoview.PhotoView;
import com.wzm.moviepic.weight.photoview.PhotoViewAttacher.OnViewTapListener;
import com.wzm.utils.FileUtils;
import com.wzm.utils.Logger;
import com.wzm.utils.NetworkUtils;
import com.wzm.utils.StringUtils;
import com.wzm.utils.UtilsTools;

import net.tsz.afinal.FinalBitmap;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class SamplePagerAdapter extends PagerAdapter {

	private Context mContext;
	private ArrayList<PicInfo> pList;	
	private FinalBitmap fb = null;
	private FinalHttp fh = null;
	private LayoutInflater  mInflater;
	private String movieid;
	private Map<Integer,Bitmap> bmap = new HashMap<Integer,Bitmap>();
	
	private AboutListAdapter alAdapter = null;
	private ListView mListview = null;
	
	
	SamplePagerAdapter(Context context,ArrayList<PicInfo> list,String mid)
	{
		mContext = context;
		bmap.clear();
		pList = list;
		mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		fb = AppManager.getInstance(mContext).getFb();
		fh = AppManager.getInstance(mContext).getFh();
		movieid = mid;
	}
	
	@Override
	public int getCount() {
		return pList.size();
	}

	@Override
	public View instantiateItem(ViewGroup container, int position) {
		
		
		//Logger.error("position:"+position);
		if(position==pList.size()-1)
		{//如果到了最后一页（广告）
			View view = mInflater.inflate(R.layout.last_item, container, false); 
			ArrayList<AdInfo> adbList = AppApplication.getInstance().getAdbList();
			if(adbList.size()>0)
			{
				final AdInfo adinfo = adbList.get(UtilsTools.getRandomInt(adbList.size()));
				ImageView ad_icon = (ImageView)view.findViewById(R.id.ad_icon);
				fb.display(ad_icon, adinfo.getIcon());
				TextView tv_name = (TextView)view.findViewById(R.id.ad_name);
				tv_name.setText(adinfo.getName());
				TextView tv_author = (TextView)view.findViewById(R.id.ad_author);
				tv_author.setText(adinfo.getCompany());
				
				TextView tv_intro = (TextView)view.findViewById(R.id.ad_intro);
				tv_intro.setText(adinfo.getIntro());
				
				//离线下载
				
				TextView ad_btn1 = (TextView)view.findViewById(R.id.tv_adbtn1);
				ad_btn1.setText(adinfo.getOpen_url_title());
				LinearLayout lly_addown = (LinearLayout)view.findViewById(R.id.lly_addown);
				
				lly_addown.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						Uri uri = Uri.parse(adinfo.getOpen_url());  
						Intent it = new Intent(Intent.ACTION_VIEW, uri);  
						mContext.startActivity(it);
						it = null;
					}
				});
				
				
				LinearLayout lly_adinfo = (LinearLayout)view.findViewById(R.id.lly_adinfo);				
				lly_adinfo.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						Intent it = new Intent(mContext,AdIntroActivity.class);
						Bundle bundle = new Bundle();
						bundle.putSerializable("adinfo", adinfo);
						it.putExtras(bundle);
						mContext.startActivity(it);
						it = null;
						((ViewPagerActivity)mContext).finish();
					}
				});				
			}
			
			
			//删除缓存
			LinearLayout lly_del = (LinearLayout)view.findViewById(R.id.lly_addel);
			lly_del.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					//Toast.makeText(mContext, movieid+"删除成功", Toast.LENGTH_SHORT).show();
					
					if(FileUtils.DeleteMovieDir(movieid))
					{
						long rowid = DBHelper.getInstance(mContext).delDownInfo(movieid);
						if(rowid==1)
						{			
							((Activity)mContext).finish();
							//notifyDataSetChanged(); 
							Toast.makeText(mContext, "清除成功", Toast.LENGTH_SHORT).show();
						}
					}else{
						Toast.makeText(mContext, "清除成功", Toast.LENGTH_SHORT).show();
						((Activity)mContext).finish();
					}				
				}
			});
			
			
			
			LinearLayout lly_backmenu = (LinearLayout)view.findViewById(R.id.lly_backtomenu);
			
			lly_backmenu.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					((ViewPagerActivity)mContext).finish();
				}
			});
			
			//相关推荐列表
			mListview = (ListView)view.findViewById(R.id.amovie_list);
			
			alAdapter = new AboutListAdapter();
			
			mListview.setAdapter(alAdapter);
			getTjMovie();
			mListview.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					// TODO Auto-generated method stub
					//Toast.makeText(mContext, "pos:"+arg2, Toast.LENGTH_SHORT).show();
					MovieInfo mi = mList.get(arg2);		
					Intent it = new Intent(mContext,MovieIntroActivity.class);
					Bundle bundle = new Bundle();
					bundle.putSerializable("movieinfo", mi);
					bundle.putString("tuijian", "tuijian");
					
//					it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					it.putExtras(bundle);
					mContext.startActivity(it);
					it = null;
					((ViewPagerActivity)mContext).finish();
				}				
			});
			
			
			
			container.addView(view, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
			return view;
		}
		
		
		
		
		View view = mInflater.inflate(R.layout.movie_item, container, false);   		
		PhotoView movie_img = (PhotoView)view.findViewById(R.id.movie_img);
		
//		if(position!=0)
//		{
//			movie_img.setScaleType(ScaleType.FIT_XY);
//		}
		
		//界面点击事件
		movie_img.setOnViewTapListener(new OnViewTapListener() {
			
			@Override
			public void onViewTap(View view, float x, float y) {
				((ViewPagerActivity)mContext).touchview();
			}
		});
		
		
		
        final PicInfo pi = pList.get(position);		
        //获取图片链接，判断是否本地有这张图
        //图片文件夹保存的位置
    	String fileDirPath = Environment.getExternalStorageDirectory().getPath()+AppConfig.MOVIESDIR+movieid+"/";
    	//图片名
    	String filename =  pi.getImage().substring(pi.getImage().lastIndexOf("/")+1);   	
    	
        if(isExists(fileDirPath+filename))
        {//本地获取
        	Bitmap bitmap = FileUtils.getLoacalBitmap(fileDirPath+filename);
        	if(bitmap!=null)
        	{
        		movie_img.setImageBitmap(bitmap);
        		bmap.put(position, bitmap);
        	}else{
        		//在线获取
        		if(NetworkUtils.getNetworkState(mContext)==NetworkUtils.NETWORN_NONE)
        		{
        			Toast.makeText(mContext, "Sorry,未检测到网络，请检查",Toast.LENGTH_SHORT).show();
        		}
//        		else{
//        		}
        		fb.display(movie_img,pi.getImage(),movie_img.getWidth(),movie_img.getHeight());

        		
        	}          	
        }else{
        	//在线获取
    		if(NetworkUtils.getNetworkState(mContext)==NetworkUtils.NETWORN_NONE)
    		{
    			Toast.makeText(mContext, "Sorry,未检测到网络，请检查",Toast.LENGTH_SHORT).show();
    		}
//        	else{
//    			
//    		}
    		fb.display(movie_img,pi.getImage(),movie_img.getWidth(),movie_img.getHeight());
        }
        
 
		
        
		
        container.addView(view, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);  
		return view;
	}
	
	
	


	@Override
	public void destroyItem(ViewGroup container, int position, Object object) {	
		View view = (View) object; 
		container.removeView(view);
		
		Bitmap bitmap = bmap.get(position);
		if(bitmap!=null)
		{
			if(!bitmap.isRecycled())
			{
				//Logger.info("回收"+position);
				bitmap.recycle();
				bitmap = null;
				bmap.remove(position);
			}
		}
		
		view = null;
	}

	@Override
	public boolean isViewFromObject(View view, Object object) {
		return view == object;
	}
	
	
	public boolean isExists(String filePath)
	{
		
    	File imgFile = new File(filePath);
		if(imgFile.exists()){
			return true;
		}	
    	return false;
	}
	
	
	
	
	ArrayList<MovieInfo> mList = new ArrayList<MovieInfo>();
	public void getTjMovie()
	{
		String cacheMovielist = ConfigCache.getUrlCache(AppConfig.GETABOUT+movieid,3600000,3600000);
        if(cacheMovielist==null)
        {
        	AjaxParams params = new AjaxParams();
    		params.put("movieid",movieid);
    		//不传参数默认获取20条
    		fh.post(AppConfig.GETABOUT,params,new AjaxCallBack<Object>() {

				@Override
				public void onStart() {
					// TODO Auto-generated method stub
					super.onStart();
				}

				@Override
				public void onSuccess(Object t) {
					// TODO Auto-generated method stub
					super.onSuccess(t);
					String sjon = t.toString();
					//Logger.info("相关电影:"+sjon);
					excuteJson(sjon,true);
				}
    			
    		}); 		
        }else{
        	//Logger.info("缓存:"+cacheMovielist);
        	excuteJson(cacheMovielist,true);
        }
	}
	
	public void excuteJson(String json,boolean isclear)
	{
		
		try {
			JSONObject result = new JSONObject(json);
			int status = result.getInt("status");
			if(status==1)
			{
				mList.clear();		
				JSONArray list = result.getJSONArray("movies");								
				for(int i=0;i<list.length();i++)
				{
					MovieInfo mi = new MovieInfo();
					JSONObject obj = list.getJSONObject(i);
					//电影id
					mi.setId(obj.getString("id"));
					//电影名字
					mi.setName(obj.getString("name"));
					//电影作者
					mi.setAuthor(obj.getString("author"));
					//电影导演
					mi.setActor(obj.getString("actor"));
					//电影介绍
					mi.setIntro(obj.getString("intro"));
					//电影大图
					mi.setBpic(obj.getString("bpic"));
					//电影小图
					mi.setSpic(obj.getString("spic"));
					//标签
					mi.setTag(obj.getString("tags"));
					//类型
					mi.setZoneid(obj.getString("zoneid"));
					//评分
					mi.setScore(obj.getString("score"));
					//上映时间
					mi.setShowtime(obj.getString("showtime"));
					mList.add(mi);
					mi = null;
				}
				alAdapter.notifyDataSetChanged();
				
				Logger.info("相关电影请求完毕："+mList.size());
			}
		} catch (JSONException e) {
			Logger.error(e.getMessage());				
		}
	}
	
	
	public class AboutListAdapter extends BaseAdapter {

		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mList.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return mList.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int arg0, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			View view = convertView;
			ViewHolder viewHolder = null;
			if(view == null)
			{
				view = mInflater.inflate(R.layout.moviename_item, parent, false); 
				viewHolder = new ViewHolder();
				viewHolder.mName = (TextView)view.findViewById(R.id.tv_movie_name);
				view.setTag(viewHolder);
			}else{
				viewHolder = (ViewHolder) view.getTag();
			}
			
			viewHolder.mName.setText(mList.get(arg0).getName());
			return view;
		}
		
	}
		
	class ViewHolder
	{
		//电影名称
		TextView mName;		
	}
	
}
